#include "servicecode/HttpRequest.h"
#include "Mylogger.hh"
#include <iostream>
#include <sstream>

 
HttpRequest::HttpRequest(const string & msg)
{
    istringstream iss(msg);
    string line;
    while(getline(iss,line)){

        if(line.find("GET") != string::npos){
            _method = "GET";
            _path = line.substr(line.find(" ")+1,line.rfind(" ")-line.find(" ")-1);
        }else if(line.find("POST") != string::npos){
            _method = "POST";
            _path = line.substr(line.find(" ")+1,line.rfind(" ")-line.find(" ")-1);
        }
        if(line.find("HTTP/1.1") != string::npos){
            _version = "HTTP/1.1";
        }
        if(line.find(":") != string::npos){
            string key = line.substr(0,line.find(":"));
            _headers[key] = line.substr(line.find(":")+1);
        }
    }
    _path = deco(_path);
}

string HttpRequest::gethttprequest(){
    ostringstream oss;
    oss<<_method<<" "<<_path<<" "<<_version<<"\n";
    for(auto par : _headers){
        oss<<par.first.c_str()<<":"<<par.second.c_str();
    }
    return oss.str();
}

string HttpRequest::deco(const string &str)
{
    ostringstream decoded;
    for (size_t i = 0; i < str.length(); ++i)
    {
        if (str[i] == '%')
        {
            // 确保有足够的字符可供解析
            if (i + 2 < str.length())
            {
                // 提取两个十六进制字符
                char hex1 = str[i + 1];
                char hex2 = str[i + 2];

                // 转换为小写以统一处理
                hex1 = std::tolower(hex1);
                hex2 = std::tolower(hex2);

                // 检查是否为有效的十六进制字符
                if (std::isxdigit(hex1) && std::isxdigit(hex2))
                {
                    // 将十六进制字符转换为数值
                    int value;
                    std::istringstream hexStream(std::string() + hex1 + hex2);
                    hexStream >> std::hex >> value;

                    // 将数值转换为字符并添加到结果
                    decoded << static_cast<char>(value);

                    // 跳过已处理的字符
                    i += 2;
                }
                else
                {
                    // 无效的十六进制字符，保留原始%
                    decoded << str[i];
                }
            }
            else
            {
                // 不完整的编码，保留原始%
                decoded << str[i];
            }
        }
        else if (str[i] == '+')
        {
            // 将+转换为空格
            decoded << ' ';
        }
        else
        {
            // 直接添加普通字符
            decoded << str[i];
        }
    }
    return decoded.str();
}
